package service

import (
	sqlc "bgs/db/sqlc"
	"bgs/util"
	"context"
	"encoding/json"
	"fmt"
	"strings"
)

// FinishWxpayApplymentParam 品牌微信进件完成参数
type FinishWxpayApplymentParam struct {
	WxpayApplymentPtr *sqlc.WxpayApplyment
	SubMchID          string
}

// FinishWxpayApplyment (主动,品牌微信进件完成)
func (s *BrandServiceImp) FinishWxpayApplyment(ctx context.Context, q *sqlc.Queries, p FinishWxpayApplymentParam) (err error) {
	slog := util.NewContextLogger(ctx, s.slog)

	brandID := p.WxpayApplymentPtr.BrandID
	_, err = q.FinishWxpayApplyment(ctx, p.WxpayApplymentPtr.ID)
	if err != nil {
		return
	}
	slog.Infof("商户进件完成,更新进件申请状态 ok")

	_, err = q.UpdateBrandExtWxpayInfo(ctx, sqlc.UpdateBrandExtWxpayInfoParams{
		BrandID:             brandID,
		IsWxpayAvailable:    true,
		WxpayMchIDAsService: sqlc.NSFromString(s.vars.MchIDAsService),
		WxpayMchIDAsSub:     sqlc.NSFromString(p.SubMchID),
	})
	if err != nil {
		return
	}
	// 清空品牌缓存
	s.ClearCache(brandID)
	slog.Infof("品牌微信进件完成=>清空品牌缓存 ok")

	slog.Infof("=品牌微信进件完成 ok")

	return
}

// SyncWxpayApplymentParam 同步微信品牌进件申请进度参数
type SyncWxpayApplymentParam struct {
	WxpayApplymentPtr *sqlc.WxpayApplyment
}

// SyncWxpayApplyment (同步微信品牌进件申请进度)
func (s *BrandServiceImp) SyncWxpayApplyment(ctx context.Context, q *sqlc.Queries, p SyncWxpayApplymentParam) (wxpayApplymentPtr *sqlc.WxpayApplyment, err error) {
	slog := util.NewContextLogger(ctx, s.slog)
	wxpayApplymentPtr = p.WxpayApplymentPtr
	applymentQueryReplyPtr, err := s.ApplymentQuery(ctx, p.WxpayApplymentPtr)
	if err != nil {
		return
	}
	oldApplyState := wxpayApplymentPtr.ApplyState.String
	newApplyState := applymentQueryReplyPtr.ApplyState

	if oldApplyState != newApplyState {
		slog.Infof("需要更新微信品牌进件申请进度 %s != %s", oldApplyState, newApplyState)
		// 更新本地wxpay_applyment
		accountValidation, err2 := json.Marshal(applymentQueryReplyPtr.AccountValidation)
		if err2 != nil {
			err = fmt.Errorf("无法marshal[AccountValidation]: %s", err.Error())
			return
		}
		auditDetails, err2 := json.Marshal(applymentQueryReplyPtr.AuditDetails)
		if err2 != nil {
			err = fmt.Errorf("无法marshal[AccountValidation]: %s", err.Error())
			return
		}
		subMchID := strings.Trim(applymentQueryReplyPtr.SubMchId, " ")

		v, err2 := q.SyncWxpayApplymentProxyResult(ctx, sqlc.SyncWxpayApplymentProxyResultParams{
			ID:                 p.WxpayApplymentPtr.ID,
			WxApplymentID:      sqlc.NSFromString(applymentQueryReplyPtr.WxApplymentId),
			ApplyState:         sqlc.NSFromString(newApplyState),
			ApplyStateDesc:     sqlc.NSFromString(applymentQueryReplyPtr.ApplyStateDesc),
			SignUrl:            sqlc.NSFromString(applymentQueryReplyPtr.SignUrl),
			AccountValidation:  sqlc.NRawMessageFromRawMessage(json.RawMessage(accountValidation)),
			WxpayMchIDAsSub:    sqlc.NSFromString(subMchID),
			AuditDetails:       sqlc.NRawMessageFromRawMessage(json.RawMessage(auditDetails)),
			LegalValidationUrl: sqlc.NSFromString(applymentQueryReplyPtr.LegalValidationUrl),
		})
		if err2 != nil {
			err = fmt.Errorf("更新微信品牌进件申请进度失败: %s", err.Error())
			return
		}
		wxpayApplymentPtr = &v
	}

	slog.Infof("同步微信品牌进件申请进度 ok")
	return
}
